<template>
  <div v-if="props.charData && props.charData.length > 0" class="gcharts" id="container">
  </div>
  <app-loading v-else />
</template>
<script setup>
import { nextTick, reactive, watch } from "vue";
import { Chart } from "@antv/g2";
const state = reactive({
  chart: null, //图表对象
  title: [
    "",
    "浏览量",
    "支付金额",
    "支付人数",
    "支付订单数",
    "注册用户",
  ],
});

const props = defineProps({
  charData: {
    type: Array,
    default: () => {
      return [];
    },
  },
  type: Number,
});

const drawChart = () => {
  state.chart = new Chart({
    container: 'container',
    autoFit: true, // 自适应宽度
    height: 350,
    padding: [30, 20, 30, 20]
  });
  // 载入数据源
  state.chart.data(props.charData);
  state.chart.scale("value", {
    min: 0,
    nice: true, // 自动调整
  });
  state.chart.scale("name", {
    range: [0, 1],
  });
  state.chart.tooltip({
    showTitle: true,
    crosshairs: {
      type: "line",
    },
    // 自定义提示信息模板
    itemTpl: `<li class="tooltip-list"><span style="color:#000;font-size:14px">${state.title[props.type]
      }：</span><span style="color:#00A850;font-size:16px">{value}</span></li>`,
  });
  state.chart.line().position("name*value");
  state.chart.point().position("name*value").size(4).shape("circle").style({
    stroke: "#fff",
    lineWidth: 1,
  });
  state.chart.render();
};
watch(
  () => props.charData,
  (newVal, oldVal) => {
    if (state.chart) {
      // 销毁画布对象
      state.chart.destroy();
    }
    if (newVal) {
      nextTick(() => {
        drawChart();
      });
    }
  }
);
</script>
<style lang="scss" scoped>
.gcharts {
  width: 100%;
  height: 100%;
}
</style>
